﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SongConverter
{
    class Program
    {
        static string ConvertSong(string text)
        {
            //grab the metadata first
            StringBuilder newSongBuilder = new StringBuilder();
            System.IO.StringWriter newSong = new System.IO.StringWriter(newSongBuilder);
            string[][] metadata = { new string[]{ "title","title" },
                                  new string[]{ "author","subtitle" },
                                  new string[]{ "ccli","subtitle" },
                                  new string[]{ "presentation","comment" },
                                  new string[]{ "copyright","comment" },
                                  new string[]{ "capo","comment" },
                                  };
            foreach (string[] meta in metadata)
            {
                string data = meta[0];
                int begin = text.ToLower().IndexOf("<" + data) + 2 + data.Length;
                int end = text.ToLower().IndexOf("</" + data);
                if (begin >= 0 && end >= 0)
                {
                    string temp = text.Substring(text.ToLower().IndexOf("<" + data) + 2 + data.Length);
                    temp = temp.Substring(0, temp.ToLower().IndexOf("</" + data));
                    newSong.WriteLine("{" + meta[1] + ":" + temp + "}");
                }
            }

            text = text.Substring(text.ToLower().IndexOf("<lyrics>") + 8);
            text = text.Substring(0, text.ToLower().IndexOf("</lyrics"));
            var lines = text.Replace("\r", "").Split('\n').ToList();
            lines.RemoveAt(0);
            string chords = "";
            bool inChorus = false;
            foreach (string line in lines)
            {
                if (line.Trim() == "")
                    continue;
                if (!line.StartsWith(" ") && chords != "")
                {
                    //if the line doesn't start with a blank (ie not lyrics) and there are chords
                    //then those belong to a comment
                    newSong.WriteLine("{comment:" + chords + "}");
                    chords = "";
                }
                if (line.StartsWith("."))
                    chords = line;
                else if (line.StartsWith("["))
                {
                    if (inChorus)
                    {
                        newSong.WriteLine("{eoc}");
                        inChorus = false;
                    }
                    newSong.WriteLine(line.Replace("[", "{comment:").Replace(']', '}'));
                    if (line.Trim().ToLower().StartsWith("[c"))
                    {
                        newSong.WriteLine("{soc}");
                        inChorus = true;
                    }
                }
                else if (line.StartsWith(";"))
                {
                    if (line.Length > 0)
                    {
                        newSong.WriteLine("{comment:" + line.Substring(1) + "}");
                    }
                }
                else
                {
                    string result = line;
                    string chord = "";
                    int offset = 0;
                    for (int i = 1; i < chords.Length; i++)
                    {
                        if (chords[i] != ' ')
                        {
                            chord += chords[i];
                        }
                        if (chords[i] == ' ' || i == chords.Length - 1)
                        {
                            if (chord != "")
                            {
                                if (i - chord.Length + offset < result.Length)
                                    result = result.Substring(0, i - chord.Length + offset) + "[" + chord + "]" + result.Substring(i - chord.Length + offset);
                                else
                                    result += chord;
                                offset += chord.Length + 2;
                                chord = "";
                            }
                        }
                    }
                    chords = "";
                    newSong.WriteLine(result);
                }
            }
            if (inChorus)
            {
                newSong.WriteLine("{eoc}");
            }
            return newSongBuilder.ToString();
        }

        // Define other methods and classes here
        static void Main(string[] args)
        {
            int numErrors = 0;
            if (args.Length == 0)
            {
                args = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory());
            }
            foreach (var file in args)
            {
                try
                {
                    if (new string[] { "", "xml", ".xml" }.Contains(System.IO.Path.GetExtension(file)))
                    {
                        string text = System.IO.File.ReadAllText(file);
                        System.IO.File.WriteAllText(System.IO.Path.GetFileNameWithoutExtension(file) + ".pro", ConvertSong(text));
                    }
                }
                catch (Exception e)
                {
                    numErrors++;
                    Console.WriteLine("Encountered a problem while converting {0}. Error message {1}. Please send the error message to mirhagk@gmail.com along with the song it failed on.", file, e.ToString());
                }
            }
            if (numErrors > 0)
                Console.ReadKey();
        }
    }
}
